package com.yupi.yupicturebackend.manager.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.yupi.yupicturebackend.config.ClientConfig;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.manager.CosUtils;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Date;


/**
 * 腾讯云对象存储工具类
 */
public abstract class PictureUploadTemplate {
    @Autowired
    private CosUtils cosUtils;
    @Resource
    private ClientConfig clientConfig;
    //文件上传
    // 将本地文件上传到 COS
    public  UploadPictureResult uploadPicture(Object file,String uploadpathPrefix) throws CosClientException, MalformedURLException {
        //1.对图片进校验
        checkPacture(file);
        //2.设置图片上传地址
        //uuid防止文件重复
        String uuid = RandomUtil.randomString(6);
        //文件名
        String pictureName =getMainName(file);

        String pathName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid,pictureName);
        String PicturePath = String.format("/%s/%s",uploadpathPrefix,pathName);
        //3.上传文件
        File tempFile = null;
        try {
            //1.创建临时文件
            tempFile = File.createTempFile(PicturePath, null);
            OjbectToFile(file,tempFile);
            //2.调用接口删除文件
            PutObjectResult putObjectResult = cosUtils.putPictureObject(PicturePath, tempFile);
            if (putObjectResult == null) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
            }
            //3.对图片进行封装
            return getUploadPictureResult(putObjectResult, PicturePath, tempFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            deleteFile(tempFile);
        }
    }

    /**
     * 对图片结果进行封装并返回封装结果->UploadPictureResult
     * @param putObjectResult 腾讯云返回结果
     * @param PicturePath 腾讯云图片路径
     * @param tempFile 临时文件
     * @return
     */
    private UploadPictureResult getUploadPictureResult(PutObjectResult putObjectResult, String PicturePath, File tempFile) {
        UploadPictureResult result = new UploadPictureResult();
        ImageInfo info = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
        //计算宽高
        int width = info.getWidth();
        int height = info.getHeight();
        double  scale = NumberUtil.round(width*1.0/height,2).doubleValue();

        result.setUrl(clientConfig.getHost() + PicturePath);
        result.setPicName(FileUtil.mainName(tempFile));
        result.setPicSize(FileUtil.size(tempFile));
        result.setPicWidth(width);
        result.setPicHeight(height);
        result.setPicScale(scale);
        result.setPicFormat(info.getFormat());

        return result;
    }

    /**
     * 删除临时文件
     * @param tempFile
     */
    private static void deleteFile(File tempFile) {
        if (tempFile != null) {
            boolean delete = tempFile.delete();
            if (!delete) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件删除失败");
            }
        }
    }

    /**
     * 获取文件名
     * @param file
     * @return
     */
    protected abstract String getMainName(Object file) ;

    /**
     * 校验图片
     * @param file
     */
    public abstract void checkPacture(Object file) throws MalformedURLException;

    /**
     * 把文件转换为File
     * @param file
     * @param tempFile
     */
    public abstract void OjbectToFile(Object file, File tempFile) throws IOException;

}






